package api

import (
	"encoding/json"
	"fmt"
	"mime/multipart"
	"net/http"
)

type Context struct {
	// origin objects
	Writer http.ResponseWriter
	Req    *http.Request
	// request info
	Path   string
	Method string
	// response info
	StatusCode int
	Params     map[string]string
	RespText   any
}

func newContext(w http.ResponseWriter, req *http.Request) *Context {
	return &Context{
		Writer: w,
		Req:    req,
		Path:   req.URL.Path,
		Method: req.Method,
		Params: make(map[string]string),
	}
}

func (c *Context) Param(key string) string {
	value, _ := c.Params[key]
	return value
}
func (c *Context) PostForm(key string) string {
	return c.Req.FormValue(key)
}
func (c *Context) Query(key string) string {
	return c.Req.URL.Query().Get(key)
}
func (c *Context) Status(code int) {
	c.StatusCode = code
}
func (c *Context) SetHeader(key string, value string) {

	c.Writer.Header().Set(key, value)
}
func (c *Context) String(format string, values ...any) {
	c.SetHeader("Content-Type", "text/plain; charset=utf-8")
	c.Status(200)
	c.RespText = []byte(fmt.Sprintf(format, values...))
	c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}

func (c *Context) JSON(obj any) {
	c.SetHeader("Content-Type", "application/json; charset=utf-8")
	c.Status(200)
	encoder := json.NewEncoder(c.Writer)
	if err := encoder.Encode(obj); err != nil {
		http.Error(c.Writer, err.Error(), 500)
	}
	c.RespText = obj

}
func (c *Context) Data(data []byte) {
	c.Status(200)
	c.RespText = data
	c.Writer.Write(data)
}

func (c *Context) HTML(html string) {
	c.SetHeader("Content-Type", "text/html; charset=utf-8")
	c.Status(200)
	c.RespText = html
	c.Writer.Write([]byte(html))
}

// Upload
// args : 参数单位为MB
// 文件上传接口,必须是POST请求/*
func (c *Context) Upload() (multipart.File, *multipart.FileHeader) {
	if c.Method != http.MethodPost {
		http.Error(c.Writer, "Invalid request method", http.StatusMethodNotAllowed)
		panic(fmt.Sprintf("Invalid request method \t%v", http.StatusMethodNotAllowed))
	}

	file, handler, err := c.Req.FormFile("file")
	if err != nil {
		http.Error(c.Writer, "Error retrieving the file", http.StatusInternalServerError)
		return nil, nil
	}
	return file, handler
}

func (c *Context) Download() {

}
